<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="经过前面几篇文章的铺垫，我们正式来探讨 Sentinel 的 entry 方法的实现流程。 即探究进入 Alibaba Sentinel 核心的一把钥匙。无论是从 Sentinel 适配 Dubbo 也好，还是 SphU 源码中的注释中能看出，对一个资源进行限流或熔断，通常需要调用 SphU 的 entry 方法，例如如下示例代码。 1234567891011121314151617public">
<meta property="og:type" content="article">
<meta property="og:title" content="寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)">
<meta property="og:url" content="https://www.codingw.net/posts/550fbf45.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="经过前面几篇文章的铺垫，我们正式来探讨 Sentinel 的 entry 方法的实现流程。 即探究进入 Alibaba Sentinel 核心的一把钥匙。无论是从 Sentinel 适配 Dubbo 也好，还是 SphU 源码中的注释中能看出，对一个资源进行限流或熔断，通常需要调用 SphU 的 entry 方法，例如如下示例代码。 1234567891011121314151617public">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020010513491784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200105135205468.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-09-27T14:43:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:07:23.704Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/2020010513491784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/550fbf45.html"/>





  <title>寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/550fbf45.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-27T22:43:35+08:00">
                2020-09-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/550fbf45.html" class="leancloud_visitors" data-flag-title="寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>经过前面几篇文章的铺垫，我们正式来探讨 Sentinel 的 entry 方法的实现流程。</p>
<p>即探究进入 Alibaba Sentinel 核心的一把钥匙。<br>无论是从 Sentinel 适配 Dubbo 也好，还是 SphU 源码中的注释中能看出，对一个资源进行限流或熔断，通常需要调用 SphU 的 entry 方法，例如如下示例代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">foo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	Entry entry = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		entry = SphU.entry(<span class="string">&quot;abc&quot;</span>);</span><br><span class="line">	&#125; <span class="keyword">catch</span> (BlockException blockException) &#123;</span><br><span class="line">		<span class="comment">// when goes there, it is blocked</span></span><br><span class="line">		<span class="comment">// add blocked handle logic here</span></span><br><span class="line">	&#125; <span class="keyword">catch</span> (Throwable bizException) &#123;</span><br><span class="line">		<span class="comment">// business exception</span></span><br><span class="line">		Tracer.trace(bizException);</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="comment">// ensure finally be executed</span></span><br><span class="line">		<span class="keyword">if</span> (entry != <span class="keyword">null</span>)&#123;</span><br><span class="line">			entry.exit();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那本文将来探讨 SphU.entry 的实现原理。SphU 类定义了很多 entry 重载方法，我们就以下面这个方法为例来探究其实现原理。</p>
<h2 id="1、SphU-entry-流程分析"><a href="#1、SphU-entry-流程分析" class="headerlink" title="1、SphU.entry 流程分析"></a>1、SphU.entry 流程分析</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Entry <span class="title">entry</span><span class="params">(String name, EntryType type, <span class="keyword">int</span> count, Object... args)</span> <span class="keyword">throws</span>  BlockException </span>&#123;  <span class="comment">// @1</span></span><br><span class="line">	<span class="keyword">return</span> Env.sph.entry(name, type, count, args);  <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：我们先来简单介绍其核心参数的含义：</p>
<ul>
<li>String name<br>资源的名称。</li>
<li>EntryType type<br>进入资源的方式，主要包含 EntryType.IN、EntryType.OUT。</li>
<li>int count<br>可以理解为本次进入需要消耗的“令牌数”。</li>
<li>Object… args<br>其他参数。</li>
</ul>
<p>代码@2：调用 Env.sph.entry 的方法，其最终会调用 CtSph 的 entry 方法。</p>
<p>接下来我们将重点查看 CtSph 的 entry 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Entry <span class="title">entry</span><span class="params">(String name, EntryType type, <span class="keyword">int</span> count, Object... args)</span> <span class="keyword">throws</span> BlockException </span>&#123;</span><br><span class="line">    StringResourceWrapper resource = <span class="keyword">new</span> StringResourceWrapper(name, type); <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">return</span> entry(resource, count, args);  <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：由于该方法用来表示资源的方式为一个字符串，故创建一个 StringResourceWrapper  对象来表示一个 Sentinel 中的资源，另外一个实现为 MethodResourceWrapper，用来表示方法类的资源。</p>
<p>代码@2：继续调用 CtSph 的另外一个 entry 重载方法，最终会调用 entryWithPriority 方法。</p>
<p>CtSph#entryWithPriority </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Entry <span class="title">entryWithPriority</span><span class="params">(ResourceWrapper resourceWrapper, <span class="keyword">int</span> count, <span class="keyword">boolean</span> prioritized, Object... args)</span> <span class="comment">// @1</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> BlockException </span>&#123;</span><br><span class="line">    Context context = ContextUtil.getContext();  <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">if</span> (context <span class="keyword">instanceof</span> NullContext) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> CtEntry(resourceWrapper, <span class="keyword">null</span>, context); </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (context == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// Using default context.</span></span><br><span class="line">        context = InternalContextUtil.internalEnter(Constants.CONTEXT_DEFAULT_NAME);</span><br><span class="line">    &#125;</span><br><span class="line">   <span class="keyword">if</span> (!Constants.ON) &#123;   <span class="comment">// @3</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> CtEntry(resourceWrapper, <span class="keyword">null</span>, context);</span><br><span class="line">    &#125;</span><br><span class="line">   </span><br><span class="line">    ProcessorSlot&lt;Object&gt; chain = lookProcessChain(resourceWrapper);   <span class="comment">// @4</span></span><br><span class="line">    <span class="keyword">if</span> (chain == <span class="keyword">null</span>) &#123;</span><br><span class="line">	    <span class="keyword">return</span> <span class="keyword">new</span> CtEntry(resourceWrapper, <span class="keyword">null</span>, context);</span><br><span class="line">    &#125;</span><br><span class="line">    Entry e = <span class="keyword">new</span> CtEntry(resourceWrapper, chain, context);     <span class="comment">// @5</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">	    chain.entry(context, resourceWrapper, <span class="keyword">null</span>, count, prioritized, args);   <span class="comment">// @6</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (BlockException e1) &#123;                                                                    <span class="comment">// @7</span></span><br><span class="line">	    e.exit(count, args);</span><br><span class="line">        <span class="keyword">throw</span> e1;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable e1) &#123;</span><br><span class="line">        RecordLog.info(<span class="string">&quot;Sentinel unexpected exception&quot;</span>, e1);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> e;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：我们先来介绍一下该方法的参数：</p>
<ul>
<li>ResourceWrapper resourceWrapper<br>资源的包装类型，可以是字符串类型的资源描述，也可以是方法类的。</li>
<li>int count<br>此次需要消耗的令牌。</li>
<li>boolean prioritized<br>是否注重优先级。</li>
<li>Object… args<br>额外参数。</li>
</ul>
<p>代码@2：获取方法调用的上下文环境，上下环境对象存储在线程本地变量：ThreadLocal 中，这里先“剧透”一下，上下文环境中存储的是整个调用链，后续文章会重点介绍。</p>
<p>代码@3：Sentinel 提供一个全局关闭的开关，如果关闭，返回的 CtEntry 中的 chain 为空，从这里可以看出，如果 chain 为空，则不会触发 Sentinel 流控相关的逻辑，从侧面也反应了该属性的重要性。</p>
<p>代码@4：为该资源加载处理链链，这里是最最重要的方法，将在下文详细介绍。</p>
<p>代码@5：根据资源ID、处理器链、上下文环境构建 CtEntry 对象。</p>
<p>代码@6：调用 chain 的 entry 方法。</p>
<p>代码@7：如果出现 BlockException ，调用 CtEntry 的 exit 方法。</p>
<h2 id="2、Sentienl-ProcessorSlot-处理链"><a href="#2、Sentienl-ProcessorSlot-处理链" class="headerlink" title="2、Sentienl ProcessorSlot 处理链"></a>2、Sentienl ProcessorSlot 处理链</h2><p>我们接下来重点看一下 lookProcessChain 方法的实现细节。<br>CtSph#lookProcessChain</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ProcessorSlot&lt;Object&gt; <span class="title">lookProcessChain</span><span class="params">(ResourceWrapper resourceWrapper)</span> </span>&#123;</span><br><span class="line">    ProcessorSlotChain chain = chainMap.get(resourceWrapper);  <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (chain == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (LOCK) &#123;</span><br><span class="line">	    chain = chainMap.get(resourceWrapper);</span><br><span class="line">            <span class="keyword">if</span> (chain == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// Entry size limit.</span></span><br><span class="line">                <span class="keyword">if</span> (chainMap.size() &gt;= Constants.MAX_SLOT_CHAIN_SIZE) &#123;        <span class="comment">// @2</span></span><br><span class="line">		    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                chain = SlotChainProvider.newSlotChain();                                      <span class="comment">// @3</span></span><br><span class="line">                Map&lt;ResourceWrapper, ProcessorSlotChain&gt; newMap = <span class="keyword">new</span> HashMap&lt;ResourceWrapper, ProcessorSlotChain&gt;(</span><br><span class="line">                        chainMap.size() + <span class="number">1</span>);</span><br><span class="line">                newMap.putAll(chainMap);</span><br><span class="line">                newMap.put(resourceWrapper, chain);</span><br><span class="line">                chainMap = newMap;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> chain;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：chainMap 一个全局的缓存表，即同一个资源 ResourceWrapper (同一个资源名称) 会共同使用同一个 ProcessorSlotChain ，即不同的线程在访问同一个资源保护的代码时，这些线程将共同使用 ProcessorSlotChain  中的各个 ProcessorSlot 。注意留意 ResourceWrapper 的 equals 方法与 hashCode 方法。</p>
<p>代码@2：这里重点想突出，如果同时在进入的资源个数超过 MAX_SLOT_CHAIN_SIZE，默认为 6000，会返回 null，则不对本次请求执行限流，熔断计算，而是直接跳过，这个点还是值得我们注意的。</p>
<p>代码@3：通过 SlotChainProvider 创建对应的处理链。</p>
<p>SlotChainProvider#newSlotChain</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ProcessorSlotChain <span class="title">newSlotChain</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (slotChainBuilder != <span class="keyword">null</span>) &#123;     <span class="comment">// @1</span></span><br><span class="line">		<span class="keyword">return</span> slotChainBuilder.build();</span><br><span class="line">        &#125;</span><br><span class="line">	slotChainBuilder = SpiLoader.loadFirstInstanceOrDefault(SlotChainBuilder.class, DefaultSlotChainBuilder.class);   <span class="comment">// @2</span></span><br><span class="line">	<span class="keyword">if</span> (slotChainBuilder == <span class="keyword">null</span>) &#123;                                                                                                                                        <span class="comment">// @3</span></span><br><span class="line">		RecordLog.warn(<span class="string">&quot;[SlotChainProvider] Wrong state when resolving slot chain builder, using default&quot;</span>);</span><br><span class="line">                slotChainBuilder = <span class="keyword">new</span> DefaultSlotChainBuilder();</span><br><span class="line">         &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		RecordLog.info(<span class="string">&quot;[SlotChainProvider] Global slot chain builder resolved: &quot;</span></span><br><span class="line">                + slotChainBuilder.getClass().getCanonicalName());</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">return</span> slotChainBuilder.build();                                                                                                                                   <span class="comment">// @4</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果 slotChainBuilder 不为空，则直接调用其 build 方法构建处理器链。</p>
<p>代码@2：如果为空，首先通过 JAVA 的 SPI 机制，尝试加载自定义的 Slot Chain 构建器实现类。如果需要实现自定义的 Chain 构建器，只需实现  SlotChainBuilder 接口，然后将其放在 classpath 下即可，如果存在多个，以找到的第一个为准。</p>
<p>代码@3：如果从 SPI 机制中加载失败，则使用默认的构建器：DefaultSlotChainBuilder。</p>
<p>代码@4：调用其 build 方法构造 Slot Chain。</p>
<p>那接下来我们先来看看 Sentinel 的 SlotChainBuilder 类体系，然后看看 DefaultSlotChainBuilder 的 build 方法。</p>
<h4 id="2-1-SlotChainBuilder-类体系"><a href="#2-1-SlotChainBuilder-类体系" class="headerlink" title="2.1 SlotChainBuilder  类体系"></a>2.1 SlotChainBuilder  类体系</h4><p><img src="https://img-blog.csdnimg.cn/2020010513491784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>主要有三个实现类，对应热点、接口网关以及普通场景。我们接下来将重点介绍 DefaultSlotChainBuilder ，关于热点限流与网关限流将在后面的文章中详细探讨。</p>
<h4 id="2-2-DefaultSlotChainBuilder-build-方法"><a href="#2-2-DefaultSlotChainBuilder-build-方法" class="headerlink" title="2.2 DefaultSlotChainBuilder build 方法"></a>2.2 DefaultSlotChainBuilder build 方法</h4><p>DefaultSlotChainBuilder#build</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultSlotChainBuilder</span> <span class="keyword">implements</span> <span class="title">SlotChainBuilder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ProcessorSlotChain <span class="title">build</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ProcessorSlotChain chain = <span class="keyword">new</span> DefaultProcessorSlotChain();</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> NodeSelectorSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> ClusterBuilderSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> LogSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> StatisticSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> AuthoritySlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> SystemSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> FlowSlot());</span><br><span class="line">        chain.addLast(<span class="keyword">new</span> DegradeSlot());</span><br><span class="line">        <span class="keyword">return</span> chain;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>就问大家激不激动，开不开心，从这些 Slot 的名字基本就能得出其含义。</p>
<ul>
<li>NodeSelectorSlot<br>主要用于构建调用链。</li>
<li>ClusterBuilderSlot<br>用于集群限流、熔断。</li>
<li>LogSlot<br>用于记录日志。</li>
<li>StatisticSlot<br>用于实时收集实时消息。</li>
<li>AuthoritySlot<br>用于权限校验的。</li>
<li>SystemSlot<br>用于验证系统级别的规则。</li>
<li>FlowSlot<br>实现限流机制。</li>
<li>DegradeSlot<br>实现熔断机制。</li>
</ul>
<span id="more"></span>

<blockquote>
<p>经过上面的方法，就构建一条 Slot 处理链。其实到这里我们就不难发现，调用 ProcessorSlotChain 的 entry 方法，就是依次调用这些 slot 的方法。关于 ProcessorSlotChain 的类层次结构就不再多说明了，其实现比较简单，大家如果有兴趣的话，可以关注这部分的实现，这里代表一类场景：一对多、责任链的设计模式。</p>
<h2 id="3、Sentinel-SphU-entry-处理流程图"><a href="#3、Sentinel-SphU-entry-处理流程图" class="headerlink" title="3、Sentinel SphU.entry 处理流程图"></a>3、Sentinel SphU.entry 处理流程图</h2><p>经过上面的探索，我们其实已经找到了 Sentinel 的关于限流、熔断核心处理逻辑的入口，就是 FlowSlot、DegradeSlot。接下来我们以一张流程图来结束本文的讲解。<br><img src="https://img-blog.csdnimg.cn/20200105135205468.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>本文的目的就是打开 Sentinel 的大门，即寻找实时数据收集、限流、熔断实现机制的入口，从而正式探寻 Sentienl 的核心实现原理，更多精彩请继续期待该专栏的后续内容。</p>
</blockquote>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/9ef855bf.html" rel="next" title="基于 raft 协议的 RocketMQ DLedger 多副本日志复制设计原理">
                <i class="fa fa-chevron-left"></i> 基于 raft 协议的 RocketMQ DLedger 多副本日志复制设计原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/12736650.html" rel="prev" title="源码阅读技巧篇：RocketMQ DLedger 多副本即主从切换专栏回顾">
                源码阅读技巧篇：RocketMQ DLedger 多副本即主从切换专栏回顾 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81SphU-entry-%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90"><span class="nav-number">1.</span> <span class="nav-text">1、SphU.entry 流程分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Sentienl-ProcessorSlot-%E5%A4%84%E7%90%86%E9%93%BE"><span class="nav-number">2.</span> <span class="nav-text">2、Sentienl ProcessorSlot 处理链</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-SlotChainBuilder-%E7%B1%BB%E4%BD%93%E7%B3%BB"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 SlotChainBuilder  类体系</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-DefaultSlotChainBuilder-build-%E6%96%B9%E6%B3%95"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 DefaultSlotChainBuilder build 方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81Sentinel-SphU-entry-%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="nav-number">3.</span> <span class="nav-text">3、Sentinel SphU.entry 处理流程图</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
